﻿using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using Rmq.Center;
using User.Api.BizExtensions;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace Out.TaskRunner.RmqWorkers
{
    public class OrderUnpickupingChkWork : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(OrderUnpickupingChkWork));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new OrderUnpickupingChkConsumer())
            {
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.OrderType == OrderType.挂号订单)
                    {
                        return ProcessRegOrder(msg.OrderId, channel);
                    }

                    return new ConsumedResult { Ack = true };
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(50);
                }
            }
        }

        private ConsumedResult ProcessRegOrder(int orderId, WrapperChannel channel)
        {
            OrderSummary order;
            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                order = ctx.ApptOrders.Where(x => x.Id == orderId).
                    Select(x => new OrderSummary
                    {
                        Id = x.Id,
                        OrderNo = x.OrderNo,
                        SumFee = x.SumFee
                    }).FirstOrDefault();
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }
            }

            //执行查询挂号状态操作
            var unpickupChkrequest = new GetOrderStatusRequest();
                unpickupChkrequest.OrderId = order.OrderNo;

                GetOrderStatusResponse unpickupChkResponse;
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("HisSp/GetApptStatus", unpickupChkrequest).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    unpickupChkResponse = responseMsg.Content.ReadAsAsync<GetOrderStatusResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内查询取号状态Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                    return new ConsumedResult
                    {
                        Ack = false,
                        Delay = 60 * 1000
                    };
                }

                if (unpickupChkResponse.ResultCode != "0")
                {
                //取号成功
                DataBaseCommandFactory.CreateDatbaseCommand()
                                       .UpdateOrderStatus(orderId, ApptOrderExtensions.OrderStatus.取号成功.ToInt32());

                // RMQ 发送退号失败的用户通知
                var msgProducer = new UserMessageProducer();
                    msgProducer.Publish(new UserMessageMsg
                    {
                        Type = UserMessageType.退号失败通知,
                        OrderId = order.Id
                    });
                }
                else
                {
                    // 查询结果为已退号
                    if (unpickupChkResponse.Status == "2")
                    {
                    //微信退号成功
                    DataBaseCommandFactory.CreateDatbaseCommand()
                        .UpdateOrderStatus(orderId, ApptOrderExtensions.OrderStatus.微信退号成功.ToInt32());

                    // RMQ 发送退号成功的用户通知
                    var msgProducer = new UserMessageProducer();
                        msgProducer.Publish(new UserMessageMsg
                        {
                            Type = UserMessageType.退号成功通知,
                            OrderId = order.Id
                        });

                        if (order.SumFee > 0)
                        {
                            // RMQ 执行退费操作
                            var refundingProducer = new OrderRefundingUnpickupSucceedProducer();
                            refundingProducer.Publish(new OrderRefundingUnpickupSucceedMsg
                            {
                                OrderType = Rmq.Center.OrderType.挂号订单,
                                OrderId = order.Id
                            });
                        }
                    }
                    // 查询结果为已取号
                    if (unpickupChkResponse.Status == "0")
                    {
                        //取号成功
                        DataBaseCommandFactory.CreateDatbaseCommand()
                            .UpdateOrderStatus(orderId, ApptOrderExtensions.OrderStatus.取号成功.ToInt32());

                    // RMQ 发送退号失败的用户通知
                    var msgProducer = new UserMessageProducer();
                        msgProducer.Publish(new UserMessageMsg
                        {
                            Type = UserMessageType.退号失败通知,
                            OrderId = order.Id
                        });
                    }
                }
            

            return new ConsumedResult
            {
                Ack = true
            };
        }

        public class OrderSummary
        {
            public int Id { get; set; }
            public string OrderNo { get; set; }
            public decimal? SumFee { get; set; }
        }
    }
}